#!/usr/bin/ruby

require "ruby-debug"

class AAData

	class Motif

		attr_reader :genes, :motif_name

		class GeneSeqs

			class SeqClass < Struct.new(:seq, :start, :strand)
				def <=>(comp_seq)
					self.start <=> comp_seq.start
				end
			end

			attr_reader :name, :seqs

			def initialize(name)
				@name 	= name
				@seqs 	= []
			end

			def add_seq(seq, start, strand)
				@seqs << SeqClass.new(seq, start, strand)
				#@seqs.sort!
			end

		end



		def initialize(seq_array, gene_array)
			@map 		= seq_array.pop[1]
			# Trim lines which aren't used
			seq_array.pop
			@motif_name = seq_array.shift

			@genes = gene_array.inject({}) do |memo, g_name|
				memo[g_name] = GeneSeqs.new(g_name)
				memo
			end

			seq_array.each do |g_a|
				@genes[gene_array[g_a[1].to_i]].add_seq(g_a[0], g_a[2].to_i, g_a[3].to_i)
			end
		end

	end
	
	def initialize(in_dat, ana_classes = [])
		@ana_classes = ana_classes

		# Split all of the data appart into arrays.
		dat_groups 		= in_dat.split("\n\n").map {|v| v.split("\n").map {|v2| v2.split("\t")} }
		@meta 			= dat_groups.shift
		@gene_names		= dat_groups.shift.map {|g| (g[1]) ? g[1] : g[0]}
		@gene_names.shift

		@motifs			= dat_groups.map {|dg| Motif.new(dg, @gene_names)}
		# debugger
	end


end


case ARGV.size
when 0
	#data = ""
	#while gets
	#	data += $_
	#	puts $_
	#end
	#AAData.new(data)
	
when 1
	AAData.new( File.open(ARGV.shift).read )
 
else
	puts "Invalid number of arguments"
end
